package com.yzd.learnjava.annotaions.database;

import java.lang.annotation.Annotation;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;

import com.yzd.learnjava.util.Print;

public class TableCreator {
	public static void main(String[] args) throws ClassNotFoundException {
		String className = "com.yzd.learnjava.annotaions.database.Member";
		Class<?> cl = Class.forName(className);
		DBTable dbTable = cl.getAnnotation(DBTable.class);
//		if(dbTable )
		
		String tableName = dbTable.name();
		if(tableName.length() < 1) {
			tableName = cl.getName().toUpperCase();
		}
		
		List<String> columnDefs = new ArrayList<String>();
		for(Field field : cl.getDeclaredFields()) {
			String columnName = null;
			Annotation[] anns = field.getDeclaredAnnotations();
			if(anns.length < 1) {
				continue;
			}
			
			if(anns[0] instanceof SQLInteger) {
				SQLInteger sInt = (SQLInteger)anns[0];
				if(sInt.name().length() < 1) {
					columnName = field.getName().toUpperCase();
				} else {
					columnName = sInt.name();
				}
				columnDefs.add(columnName + " INT" + getContraints(sInt.constraints()));
			}
			
			if(anns[0] instanceof SQLString) {
				SQLString ss = (SQLString)anns[0];
				if(ss.name().length() < 1) {
					columnName = field.getName().toUpperCase();
				} else {
					columnName = ss.name();
				}
				columnDefs.add(columnName + " VARCHAR(" + ss.value() + ")" + getContraints(ss.constraints()));
			}
			
			StringBuilder sb = new StringBuilder("CREATE TABLE " + tableName + "(");
			for(String s : columnDefs) {
				sb.append("\n    " + s + ",");
			}
			
			String tableCreate = sb.substring(0, sb.length() - 1) + ")";
			Print.print("Table Create SQL for" + className + " is :\n" + tableCreate);
		}
		
		
	}
	
	private static String getContraints(Constraints con) {
		String contraints = "";
		if(!con.allowNull()) {
			contraints += " NOT NULL";
		}
		
		if(con.primaryKey()) {
			contraints += " PRIMARY KEY";
		}
		
		if(con.unique()) {
			contraints += " UNIQUE";
		}
		
		return contraints;
	}
}
